package lib

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
)

type QiniuConfig struct {
	AccessKey string
	SecretKey string
	Bucket    string
}

type QiniuPutRet struct {
	Key    string
	Hash   string
	Fsize  int
	Bucket string
	Name   string
}

type AliConfig struct {
	AccessKey string
	SecretKey string
	Endpoint  string
	Bucket    string
}

var (
	Config   *viper.Viper
	QiniuCfg *QiniuConfig
	AliCfg   *AliConfig
)

func init() {
	Config = NewConfig()
	QiniuCfg = GetQiniuConfig(Config)
	AliCfg = GetAliConfig(Config)
}

func NewConfig() *viper.Viper {
	workDir, _ := os.Getwd()
	viper.SetConfigName("config")
	viper.SetConfigType("yml")
	viper.AddConfigPath(filepath.Join(workDir, "config"))

	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}

	return viper.GetViper()
}

func GetQiniuConfig(Config *viper.Viper) *QiniuConfig {
	res := &QiniuConfig{}
	res.AccessKey = Config.GetString("oss.qiniu.access_key")
	res.SecretKey = Config.GetString("oss.qiniu.secret_key")
	res.Bucket = Config.GetString("oss.qiniu.bucket")
	return res
}

func GetAliConfig(Config *viper.Viper) *AliConfig {
	res := &AliConfig{}
	res.AccessKey = Config.GetString("oss.ali.access_key")
	res.SecretKey = Config.GetString("oss.ali.secret_key")
	res.Bucket = Config.GetString("oss.ali.bucket")
	res.Endpoint = Config.GetString("oss.ali.endpoint")
	return res
}

func HandleError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}
